import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Inject,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  @Inject(Reflector)
  private readonly reflector: Reflector;

  @Inject(JwtService)
  private readonly jwtService: JwtService;

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();

    const response = context.switchToHttp().getResponse()

    const requiredLogin = this.reflector.getAllAndOverride(`require-login`, [
      context.getClass(),
      context.getHandler(),
    ]);

    if (!requiredLogin) {
      return true;
    }

    const authorization = request.headers.authorization;

    if (!authorization) {
      throw new HttpException(`用户未登录`, HttpStatus.UNAUTHORIZED);
    }

    try {
      const token = (authorization as string).split(' ')[1];
      const data = this.jwtService.verify(token);

      request.user = {
        userId: data.userId,
        username: data.username,
      };

      response.header('token', this.jwtService.sign({
        userId: data.userId,
        username: data.username
      }, {
        expiresIn: '7d'
      }))

      return true;
    } catch (error) {
      throw new UnauthorizedException('token 失效，请重新登录');
    }
  }
}
